package com.fish.yssb.ui.page.activity.other;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.fish.yssb.Consts;
import com.fish.yssb.R;
import com.fish.yssb.api.retData;
import com.fish.yssb.api.setApi;
import com.fish.yssb.app.BaseApp;
import com.fish.yssb.data.model.LoginUser;
import com.fish.yssb.db.RealmDb;
import com.fish.yssb.db.bean.BaseInfoTable;
import com.fish.yssb.db.bean.LogInfoTable;
import com.fish.yssb.ui.page.activity.base.BaseActivity;
import com.fish.yssb.ui.page.adapter.LogParaAdapter;
import com.fish.yssb.ui.page.adapter.constParaAdapter;
import com.fish.yssb.ui.page.dialog.PublicNoticeDialog;
import com.fish.yssb.ui.page.util.PrefeneceUtil;
import com.fish.yssb.ui.page.util.TopToastUtil;
import com.hy.srv101.CmdDataCell;
import com.jaeger.library.StatusBarUtil;
import com.syd.oden.circleprogressdialog.core.CircleProgressDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * A login screen that offers login via email/password.
 */
public class LogActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = LogActivity.class.getSimpleName();

    LinearLayout tv_back,ll_search;
    TextView tv_toptitle,tv_set,tv_save,s_time,e_time;
    private TimePickerView pvTime;
    private  int timeType =1;
    private RecyclerView recyclerView;
    private LogParaAdapter adapter;
    private  PublicNoticeDialog noticeDialog;
    private RelativeLayout ll_para_1, ll_para_2, ll_para_3;
    private CircleProgressDialog circleProgressDialog;

    private TextView btn_2;
    private  ArrayList<LogInfoTable> arrayList;
    public static void start(Context context) {
        Intent intent = new Intent(context, LogActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setDarkMode(this);
        setContentView(R.layout.activity_log_list);
        initview();
        EventBus.getDefault().register( this );
        circleProgressDialog = new CircleProgressDialog(LogActivity.this);
        circleProgressDialog.setText("命令执行中");
//        int ret =  setApi.getInstance(this).r_const_para();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister( this );
    }




    //初始化视图
    @SuppressLint("WrongViewCast")
    private void initview() {
        //登录层、下拉层、其它登录方式层
        recyclerView = (RecyclerView) findViewById(R.id.recylerview);
        recyclerView.setHasFixedSize(true);



        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter = new LogParaAdapter());

        adapter.replaceAll(getData());

        tv_back = findViewById(R.id.tv_back);
        tv_set = findViewById(R.id.tv_set);
        tv_save = findViewById(R.id.tv_save);
        s_time = findViewById(R.id.s_time);
        e_time = findViewById(R.id.e_time);
        btn_2 = findViewById(R.id.btn_2);

        s_time.setOnClickListener(this);
        e_time.setOnClickListener(this);
        tv_set.setOnClickListener(this);
        tv_back.setOnClickListener(this);

        btn_2.setOnClickListener(this);

        ll_search = findViewById(R.id.ll_search);
        ll_search.setOnClickListener(this);
//        tv_save.setOnClickListener(this);
//        int ret =  setApi.getInstance(this).r_const_para();
        initTimePicker();
    }

    @Subscribe
    public void onEvent(final retData result) {

    };


    private final static String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    public String byteToInt(byte[] bytes)
    {
        String str = "";
        int num = 0;
        switch (bytes.length)
        {
            case 1:
                 num = bytes[0] & 0xFF;
                break;
            case 2:
                 num = bytes[0] & 0xFF |(bytes[1] & 0xFF) << 8 ;
                break;
            case 3:
                num = bytes[0] & 0xFF |(bytes[1] & 0xFF) << 8 |(bytes[2] & 0xFF) << 16;
                break;
                case 4:
                    num = bytes[0] & 0xFF |(bytes[1] & 0xFF) << 8  |(bytes[2] & 0xFF) << 16 |(bytes[3] & 0xFF) << 24;
            break;
        }

        str = num+"";
        return str;
    }
    public String byteToHex(int n) {

        if(n>65535)
        {
            n = n-65535;
        }

        int m = n/256;
        int m1= n%256;


        int d1 = m/16;
        int d2 = m%16;
        int d3 = m1 / 16;
        int d4 = m1 % 16;
        return hexArray[d3] + hexArray[d4]+hexArray[d1] + hexArray[d2];
    }


    @Override
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.s_time:
                timeType = 1;
                pvTime.show(view);
                break;
            case R.id.e_time:
                timeType = 2;
                pvTime.show(view);
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.btn_2:
            case R.id.ll_search:

                if(sl_time== -1 && el_time == -1)
                {
                    adapter.replaceAll(getData());
                    adapter.notifyDataSetChanged();
                }else {
//                if(sl_time == -1)
//                {
                    adapter.replaceAll(getData1());
                    adapter.notifyDataSetChanged();
//                }
                }
                break;

            default:
                break;
        }
    }

    public ArrayList<LogInfoTable> getData1()
    {
        ArrayList<LogInfoTable> list = new ArrayList<>();
        final LoginUser user = BaseApp.getInstance().user;
        if("管理员".equalsIgnoreCase(user.getUserType())) {

            list =(ArrayList<LogInfoTable>) RealmDb.getInstance().queryRealmObjectsByDataBy(LogInfoTable.class, sl_time, el_time);

        }else{
            list =(ArrayList<LogInfoTable>) RealmDb.getInstance().queryRealmObjectsByDataBy_byName(LogInfoTable.class, sl_time, el_time,user.getUserName());
        }

        String limmit =  PrefeneceUtil.getData("para3_et_log_max","30",false);
        Collections.reverse(list);

//        int num = 1;
//        try{
//            num = Integer.parseInt(limmit);
//            list=list.subList(0, num);
//        }catch (Exception ex)
//        {
//            ex.printStackTrace();
//        }
        return list;
    }

    public ArrayList<LogInfoTable> getData()
    {
        ArrayList<LogInfoTable> list = new ArrayList<>();
        final LoginUser user = BaseApp.getInstance().user;
        if("管理员".equalsIgnoreCase(user.getUserType())) {

            list = (ArrayList<LogInfoTable>) RealmDb.getInstance().queryRealmObjects_log(LogInfoTable.class);

        }else{
            list = (ArrayList<LogInfoTable>) RealmDb.getInstance().queryRealmObjects_log_byName(LogInfoTable.class,user.getUserName());
        }
        Collections.reverse(list);
        return list;
    }

    private long sl_time = -1,el_time = 9999999999999999l;
    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(LogActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(context, getTime(date), Toast.LENGTH_SHORT).show();
                Log.i("pvTime", "onTimeSelect");
//                TopToastUtil.getInstance(getActivity(),R.layout.showdialog).showShortToast("时间同步成功");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              String dateString = formatter.format(date);
              if(timeType ==1)
              {
                  s_time.setText(dateString);
                  sl_time = date.getTime();
              }else {
                  e_time.setText(dateString);
                  el_time = date.getTime();
              }

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");

                    }
                })
                .setTitleText("查询设置")
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

}

